# -*- coding: utf-8 -*-
from playwright.sync_api import sync_playwright, expect, Page
import os
import time
from utils.tools import get_path

# URL_L = "https://pingcode.com/signin"
URL_L = "https://sqwl20250424040007148.pingcode.com/"

def page_login_save_cookies(page: Page, user_name: str, password: str):
    """
    通过页面登录
    :param page: page对象
    :param usernaem:
    :param password:
    :return:
    """

    # os.path.getatime(f"{user_name}.txt" 文件的创建时间
    # page.pause()

    if os.path.exists(get_path(f"/.auth/{user_name}.txt")) and int(time.time() - os.path.getatime(get_path(f"/.auth/{user_name}.txt"))) < 86400:
        with open(get_path(f"/.auth/{user_name}.txt")) as f:
            cookies = f.read()
        cookies = eval(cookies)  # 转换文档原格式
        page.context.add_cookies(cookies)
        page.goto(URL_L)
    else:
        page.goto(URL_L)
        page.get_by_role("textbox", name="请输入手机号/邮箱").type(user_name, delay=20)
        page.get_by_role("textbox", name="请输入登录密码").fill(password)
        page.get_by_role("button", name="登录").click()
        page.wait_for_timeout(5000)
        expect(page.locator('.avatar-default').first).to_be_visible()  # to_be_visible 判断是否存在
        cookies = page.context.cookies()  # page.context.cookies() 获取登录的cookie
        with open(get_path(f"/.auth/{user_name}.txt"), "w") as f:
            f.write(str(cookies))

def 跳转(page:Page,path:str):
    if path[0] != '/':
        path = f'/{path}'
    page.goto(f'{page.url.split(".com")[0]}.com{path}')